﻿using SmartMotion.Core;
using SmartMotion.Properties;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using DevComponents.AdvTree;
using Force.DeepCloner;
using Microsoft.VisualBasic.FileIO;
using Sunny.UI;
using WeifenLuo.WinFormsUI.Docking;

namespace SmartMotion.Pages.DockPages
{
    public partial class FrmToolBox : DockContent
    {
        #region 字段

        private TreeNode _clickNode;
        private ToolMgr _toolMgr;
        private List<ActionItem> _searchTools;

        #endregion
        public FrmToolBox()
        {
            InitializeComponent();
        }

        private void FrmToolBox_Load(object sender, EventArgs e)
        {
            HideOnClose = true;
            _toolMgr = ToolMgr.Ins;
            _searchTools = new List<ActionItem>();

            ShowTools();
        }

        private void FrmToolBox_Resize(object sender, EventArgs e)
        {
            txtSearchTool.Height = 30;
        }

        private void ShowTools()
        {
            //加载工具
            _toolMgr.LoadTools();
            //把树清空
            tv.Nodes.Clear();
            //图标清空
            imageList1.Images.Clear();
            //添加工具箱分组图标
            imageList1.Images.Add(Resources.ToolBox);
            foreach (var image in _toolMgr.Images)
            {
                imageList1.Images.Add(image.Key, image.Value); //添加所有工具的图标
            }
            //获得所有分组的名称
            var groups = _toolMgr.Tools.Select(tool => tool.Group).ToList().Distinct().ToList();

            //遍历分组
            foreach (var groupName in groups)
            {
                //创建分组节点
                var gpNode = new TreeNode
                {
                    Text = groupName
                };
                //创建子节点
                foreach (var tool in _toolMgr.Tools)//遍历所有已加载的工具
                {
                    //如果工具的分组和当前分组名称相同，就添加到树
                    if (tool.Group == groupName)
                    {
                        //创建工具节点
                        TreeNode toolNode = new TreeNode(tool.ItemName);

                        #region 准备工具图标索引

                        int imageIndex = -1;
                        for (int i = 0; i < imageList1.Images.Keys.Count; i++)
                        {
                            var img = imageList1.Images.Keys[i];//图片的key
                            if (img == tool.Icon)
                            {
                                imageIndex = i;
                                break;
                            }
                        }

                        toolNode.ImageIndex = imageIndex;
                        toolNode.SelectedImageIndex = imageIndex;

                        #endregion 准备工具图标索引

                        //将工具节点添加到分组节点
                        gpNode.Nodes.Add(toolNode);
                    }
                }

                //将分组节点添加到树
                tv.Nodes.Add(gpNode);
            }
            tv.ExpandAll();
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            switch (e.Button)
            {
                case MouseButtons.Left:
                    break;

                case MouseButtons.None:
                    break;

                case MouseButtons.Right:
                    _clickNode = tv.GetNodeAt(e.X, e.Y);
                    break;

                case MouseButtons.Middle:
                    break;

                case MouseButtons.XButton1:
                    break;

                case MouseButtons.XButton2:
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        private void 创建工具ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            #region 获得分组名称

            string groupName;
            if (_clickNode != null)
            {
                groupName = _clickNode.Nodes.Count > 0 ? _clickNode.Text : _clickNode.Parent.Text;
            }
            else
            {
                groupName = "Default";
            }

            #endregion 获得分组名称

            var frmCreateTool = new FrmCreateTool(groupName);
            frmCreateTool.ShowDialog();

            ShowTools();
        }

        private void txtSearchTool_TextChanged(object sender, EventArgs e)
        {
            string txtSearch = txtSearchTool.Text.ToLower();
            _searchTools.Clear();
            foreach (var toolMgrTool in _toolMgr.Tools)
            {
                if (toolMgrTool.ItemName.ToLower().Contains(txtSearch))
                {
                    _searchTools.Add(toolMgrTool);
                }
            }

            tv.Nodes.Clear();
            List<string> groups = _searchTools.Select(tool => tool.Group).ToList().Distinct().ToList();
            //遍历分组
            foreach (var groupName in groups)
            {
                //创建分组节点
                var gpNode = new TreeNode
                {
                    Text = groupName
                };
                //创建子节点
                foreach (var tool in _searchTools)//遍历所有已加载的工具
                {
                    //如果工具的分组和当前分组名称相同，就添加到树
                    if (tool.Group == groupName)
                    {
                        //创建工具节点
                        TreeNode toolNode = new TreeNode(tool.ItemName);

                        #region 准备工具图标索引

                        int imageIndex = -1;
                        for (int i = 0; i < imageList1.Images.Keys.Count; i++)
                        {
                            var img = imageList1.Images.Keys[i];//图片的key
                            if (img == tool.Icon)
                            {
                                imageIndex = i;
                                break;
                            }
                        }

                        toolNode.ImageIndex = imageIndex;
                        toolNode.SelectedImageIndex = imageIndex;

                        #endregion 准备工具图标索引

                        //将工具节点添加到分组节点
                        gpNode.Nodes.Add(toolNode);
                    }
                }

                //将分组节点添加到树
                tv.Nodes.Add(gpNode);
            }
            tv.ExpandAll();


        }

        private void tv_ItemDrag(object sender, ItemDragEventArgs e)
        {
            var node = (TreeNode) e.Item;
            if (node==null) return;
            string toolName = node.Text;
            ActionItem dragTool = _toolMgr.Tools.Find(t => t.ItemName == toolName);

            ActionItem newTool = dragTool.DeepClone();
            newTool.Name = dragTool.ItemName;
            newTool.Description = "";
            //把工具转化为AdvTree的节点
            Node advNode = CreateNodeFromItem(newTool);
            DoDragDrop(advNode, DragDropEffects.Move);

        }   

        Node CreateNodeFromItem(ActionItem item)
        {
            Node node = new Node(item.ItemName);//自定义名称，可以改
            node.Tag = item;
            node.Cells.Add(new Cell() {CheckBoxVisible = true,Checked = item.InUse});
            var cell = new Cell(item.ItemName);
            cell.Images.Image = item.IconImage;
            node.Cells.Add(cell);//图标+名称
            node.Cells.Add(new Cell(item.State));
            node.Cells.Add(new Cell(item.Time.ToString()));
            node.Cells.Add(new Cell(item.Description));

            return node;
        }

        private void 删除工具ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_clickNode == null) return;

            if (UIMessageBox.ShowAsk($"是否将流程[{_clickNode.Text}]放入回收站?"))
            {
                string filePath = $"{_toolMgr.Path}{_clickNode.Text}.tool";
                if (File.Exists(filePath))
                {
                    Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(filePath,
                        Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
                        RecycleOption.SendToRecycleBin);
                    ShowTools();
                }
            }
        }
    }   
}